package com.zmx.patientend.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.patientend.BaseActivity;
import com.zmx.patientend.R;
import com.zmx.patientend.adapter.DoctorClassificationAdapter;
import com.zmx.patientend.adapter.DoctorItemAdapter;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.pojo.Department;
import com.zmx.patientend.pojo.DepartmentCategory;
import com.zmx.patientend.pojo.Doctor;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 所有医生列表
 */
public class AllDoctorActivity extends BaseActivity {


    private LinearLayout layout;

    private DoctorClassificationAdapter adapter;
    private List<DepartmentCategory> dps;
    private RecyclerView recyclerView, re_doctor;

    private RefreshLayout mRefreshLayout;
    private String id = "0";//科室的id

    private DoctorItemAdapter doctorItemAdapter;
    private List<Doctor> doctors;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_all_doctor;
    }

    @Override
    protected void initViews() {

        setToolbar(R.id.tool_bar);

        //加载提示框
        showLoadingView("数据加载中...");

        doctorItemAdapter = new DoctorItemAdapter(this);
        re_doctor = findViewById(R.id.re_doctor);
        re_doctor.setLayoutManager(new LinearLayoutManager(this));
        re_doctor.setAdapter(doctorItemAdapter);
        doctors = new ArrayList<>();
        doctorItemAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                String did = doctors.get(listPosition).getMember_id()+"";
                //目前Activity→目标Activity
                Intent intent = new Intent(mActivity,DoctorDetailsActivity.class);
                intent.putExtra("doctor_id",did);
                intent.putExtra("class_id",id);
                intent.putExtra("hosp_id",doctors.get(listPosition).getHosp_id()+"");
                startActivity(intent);

            }
        });
        dps = new ArrayList<>();
        layout = findViewById(R.id.layout);
        recyclerView = findViewById(R.id.recycler_view);
        LinearLayoutManager layout = new LinearLayoutManager(this);
        layout.setOrientation(LinearLayoutManager.HORIZONTAL);//设置为横向排列
        recyclerView.setLayoutManager(layout);

        // 开启自动加载功能
        mRefreshLayout = findViewById(R.id.refreshLayout);
        mRefreshLayout.setEnableAutoLoadMore(true);
        mRefreshLayout.setOnRefreshListener(refreshLayout -> {

            getAllDoctor();

        });

        mRefreshLayout.setOnLoadMoreListener(refreshLayout -> {

            handler.sendEmptyMessage(3);

        });

        getData();

    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    dismissLoadingView();

                    try {

                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        JSONArray array = jsonObject.getJSONArray("data");

                        Gson g = new Gson();
                        for (int i = 0; i < array.length(); i++) {

                            JSONObject object = array.getJSONObject(i);
                            //获取第一个科室的id
                            if (i == 0) {
                                id = object.getString("id");
                            }

                            DepartmentCategory d = g.fromJson(object.toString(), DepartmentCategory.class);
                            dps.add(d);

                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    dismissLoadingView();
                    layout.setVisibility(View.VISIBLE);
                    adapter = new DoctorClassificationAdapter(dps, mActivity);
                    recyclerView.setAdapter(adapter);
                    adapter.setGetListener(position -> {
//                把点击的下标回传给适配器 确定下标
                        adapter.setmPosition(position);
                        adapter.notifyDataSetChanged();
                        id = dps.get(position).getId() + "";
                        //触发自动刷新
                        mRefreshLayout.autoRefresh();
                        getAllDoctor();

                    });

                    //触发自动刷新
                    mRefreshLayout.autoRefresh();
                    break;

                case 2:
                    doctors.clear();

                    Log.e("内容",""+msg.obj.toString());
                    JSONObject jsonObject = null;


                    try {
                        jsonObject = new JSONObject(msg.obj.toString());
                        JSONArray array = jsonObject.getJSONArray("data");

                        Gson g = new Gson();
                        for (int i = 0; i < array.length(); i++) {

                            JSONObject object = array.getJSONObject(i);
                            Doctor c = g.fromJson(object.toString(), Doctor.class);
                            doctors.add(c);

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    doctorItemAdapter.setListAndNotifyDataSetChanged(doctors);//就是设置list然后刷新
                    //刷新加载
                    mRefreshLayout.finishRefresh(true);
                    break;
                case 3:

                    //刷新加载
                    mRefreshLayout.finishLoadMore(true);
                    break;
            }

        }
    };

    /**
     * 获取科室列表
     */
    public void getData() {


        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        Log.e("854545", "'" + AllUtil.md5(sing(null)));
        params.put("sign", AllUtil.md5(sing(null)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getAllClass");
        params.put("data", "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 1, 404);

    }

    /**
     * 获取某个科室下的所有医生
     */
    public void getAllDoctor() {

        List<String> l = new ArrayList<>();
        l.add(id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getClassDoctor");
        params.put("data[class_id]", id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 2, 404);

    }

}
